package com.kedacom.ctsp.authority.controller;

import com.google.common.base.Joiner;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.URLEncoder;

@Api(tags = "rbac-authz", description = "文件下载")
@Slf4j
@RequestMapping
public class AuthorityFileController {

    public static final String USER_AGENT = "User-Agent";

    public static final String FIRE_FOX = "firefox";

    @Value("${ctsp.authz.security.file.template.path:template/}")
    private String templatePath;

    @GetMapping("/download/template/{fileName:.+}")
    @ApiOperation("下载文件")
    public void down(@PathVariable String fileName, HttpServletRequest request, HttpServletResponse response) {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        String downLoadPath = null;

        try {
            // firefox浏览器
            if (request.getHeader(USER_AGENT).toLowerCase().indexOf(FIRE_FOX) > 0) {
                fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
            } else {
                // 其他浏览器包括IE浏览器和google浏览器
                fileName = URLEncoder.encode(fileName, "UTF-8");
            }

            response.setHeader("conent-type", "application/octet-stream");
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            File file = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + templatePath + fileName);

            bis = new BufferedInputStream(new FileInputStream(file));
            bos = new BufferedOutputStream(response.getOutputStream());
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
            bis.close();
            bos.close();
        } catch (Exception e) {
            log.error("AuthorityFileController.downLoad exception:{}", e.getMessage());
        }

    }
}
